package com.leoman.controller;

import com.leoman.common.exception.GeneralExceptionHandler;
import com.leoman.controller.common.CommonController;
import com.leoman.core.Constant;
import com.leoman.core.ErrorType;
import com.leoman.core.bean.Result;
import com.leoman.entity.AdminUser;
import com.leoman.entity.CompanyUser;
import com.leoman.service.AdminUserService;
import com.leoman.service.CompanyUserService;
import com.leoman.utils.CodeUtils;
import com.leoman.utils.Md5Util;
import com.leoman.utils.WebUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 初始化控制层
 * Created by 涂奕恒 on 2016/10/18.
 */
@Controller
@RequestMapping(value = "")
public class IndexController extends CommonController {

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private CompanyUserService companyUserService;

    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request, String error, ModelMap model) {
        adminUserService.loginOut(request);
        request.getSession().setAttribute(Constant.CURRENT_USER_TYPE, "admin");

        if (StringUtils.isNotBlank(error)) {
            model.addAttribute("error", error);
        }
        return "登录";
    }

    @RequestMapping(value = "/company/login")
    public String companyLogin(HttpServletRequest request, String error, ModelMap model) {
        adminUserService.loginOut(request);
        request.getSession().setAttribute(Constant.CURRENT_USER_TYPE, "company");

        if (StringUtils.isNotBlank(error)) {
            model.addAttribute("error", error);
        }
        return "company/登录";
    }

    @RequestMapping(value = "/login/register")
    public String register(HttpServletRequest request) {
        request.getSession().removeAttribute("error");
        return "注册";
    }

    @RequestMapping(value = "/login/check")
    public String checkLogin(HttpServletRequest request,
                             String account,
                             String password,
                             String mobile,
                             String code,
                             ModelMap model) {
        String userType = (String) request.getSession().getAttribute(Constant.CURRENT_USER_TYPE);

        if (StringUtils.isNotBlank(userType) && userType.equals("admin")) {
            // 验证码
            if (!code.equalsIgnoreCase((String) request.getSession().getAttribute("code"))) {
                model.addAttribute("error", "验证码不正确");
                return "redirect:/login";
            }

            AdminUser adminUser = adminUserService.loginIn(request, account, Md5Util.md5(password));
            if (null != adminUser) {
                return "redirect:/backend/dashboard";
            }
        } else {
            CompanyUser companyUser = companyUserService.getInfoByMobile(mobile);
            if (null != companyUser) {
                if (companyUser.getPassword().equals(Md5Util.md5(password))) {
                    request.getSession().setAttribute(Constant.CURRENT_ADMIN_USER, companyUser);

                    return "redirect:/company/dashboard";
                }
            }
        }

        model.addAttribute("error", "用户名或密码错误!");
        return "redirect:/login";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request) {
        String userType = (String) request.getSession().getAttribute(Constant.CURRENT_USER_TYPE);

        adminUserService.loginOut(request);

        if (StringUtils.isNotBlank(userType) && userType.equals("admin")) {
            return "登录";
        } else {
            return "company/登录";
        }
    }

    @RequestMapping(value = "/backend")
    public String indexBackend() {
        return "redirect:/backend/dashboard";
    }

    @RequestMapping(value = "/company")
    public String indexCompany() {
        return "redirect:/company/dashboard";
    }

    @RequestMapping(value = "/")
    public String index(HttpServletRequest request) {
        String userType = (String) request.getSession().getAttribute(Constant.CURRENT_USER_TYPE);

        if (StringUtils.isNotBlank(userType) && userType.equals("admin")) {
            return "redirect:/backend/dashboard";
        } else {
            return "redirect:/company/dashboard";
        }
    }

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/login/getIdCode")
    public void getIdCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 生成验证码
            CodeUtils.getIdCode(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检测当前登录人旧密码是否正确
     */
    @RequestMapping("/check/oldPwd")
    public void checkOldPwd(HttpServletRequest request,
                            HttpServletResponse response,
                            String oldPwd) {
        String userType = (String) request.getSession().getAttribute(Constant.CURRENT_USER_TYPE);

        Map<String, String> result = new HashMap<>();
        if (StringUtils.isNotBlank(userType) && userType.equals("admin")) {
            AdminUser adminUser = (AdminUser) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);
            if (!adminUser.getPassword().equals(Md5Util.md5(oldPwd))) {
                result.put("error", "旧密码不正确!");
            } else {
                result.put("ok", "");
            }
        } else {
            CompanyUser companyUser = (CompanyUser) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);
            if (!companyUser.getPassword().equals(Md5Util.md5(oldPwd))) {
                result.put("error", "旧密码不正确!");
            } else {
                result.put("ok", "");
            }
        }

        WebUtil.print(response, result);
    }

    @RequestMapping("/modifyPwd")
    public void modifyPwd(HttpServletRequest request,
                          HttpServletResponse response,
                          String oldPwd,
                          String newPwd) {
        String userType = (String) request.getSession().getAttribute(Constant.CURRENT_USER_TYPE);
        AdminUser adminUser = null;
        CompanyUser companyUser = null;
        Boolean flag = false;

        try {
            if (StringUtils.isNotBlank(userType) && userType.equals("admin")) {
                adminUser = (AdminUser) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);
                // 管理员
                if (null != adminUser) {
                    if (adminUser.getPassword().equals(Md5Util.md5(oldPwd))) {
                        adminUser.setPassword(Md5Util.md5(newPwd));
                        adminUserService.update(adminUser);
                        System.out.println("管理员修改密码");
                        flag = true;
                    }
                }
            } else {
                companyUser = (CompanyUser) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);
                // 企业用户
                if (null != companyUser) {
                    if (companyUser.getPassword().equals(Md5Util.md5(oldPwd))) {
                        companyUser.setPassword(Md5Util.md5(newPwd));
                        companyUserService.update(companyUser);
                        System.out.println("企业用户修改密码");
                        flag = true;
                    }
                }
            }

            if (null != adminUser || null != companyUser) {
                if (flag) {
                    adminUserService.loginOut(request);
                    WebUtil.printApi(response, Result.successApi("修改密码成功！请重新登录！"));
                } else {
                    WebUtil.printApi(response, Result.failureApi("旧密码错误，修改密码失败！"));
                }
            } else {
                WebUtil.printApi(response, Result.failureApi("当前用户未登录！"));
            }
        } catch (Exception e) {
            GeneralExceptionHandler.log("修改密码失败", e);
            WebUtil.print(response, Result.failureApi(ErrorType.ERROR_BASE));
        }
    }


    /**
     * 企业用户
     */
    @RequestMapping(value = "/company/login/check")
    public String companyCheckLogin(HttpServletRequest request,
                                    String mobile,
                                    String password,
                                    ModelMap model) {
        CompanyUser companyUser = companyUserService.getInfoByMobile(mobile);
        if (null != companyUser) {
            if (companyUser.getPassword().equals(Md5Util.md5(password))) {
                request.getSession().setAttribute(Constant.CURRENT_ADMIN_USER, companyUser);

                return "redirect:/company/dashboard";
            }
        }

        model.addAttribute("error", "用户名或密码错误!");
        return "redirect:/company/login";
    }
}
